from psycopg2 import pool
from app.tools.utils import error_info
import pymysql
from DBUtils.PooledDB import PooledDB

# click house 第三方包
from clickhouse_sqlalchemy import make_session
from sqlalchemy import create_engine

import app.tools.sm_config_reader as sm_config
dsn = sm_config.Sqlserver_dsn

class PgsqlPool:
    def __init__(self, config):
        self.pool = None
        self.config = config
        self.init()

    def init(self):
        if self.pool is not None:
            return

        try:
            self.pool = pool.SimpleConnectionPool(
                minconn=2,  # 最小连接数
                maxconn=5,  # 最大连接数
                host=self.config['host'],  # 服务器
                port=self.config['port'],  # 端口
                user=self.config['user'],  # 用户名
                password=self.config['password'],  # 密码
                database=self.config['database'],  # 数据库
                keepalives=1,  # 不知道是啥
                keepalives_idle=30,  # 操作系统向客户端发送一个消息后无网络活动的时间
                keepalives_interval=10,  # 未被客户端确认收到的消息应重新传输的时间长度
                keepalives_count=5  # 指定服务器到客户端的连接被认为中断之前可以丢失的消息的数量
            )
        except Exception as err:
            self.pool = None
            error_info(err)

    def connect(self):
        # 如果pool为空,先恢复一下连接池
        if self.pool is None:
            self.init()

        # 恢复连接池失败
        if self.pool is None:
            return None, None

        conn = self.pool.getconn()
        cursor = conn.cursor()
        return conn, cursor

    def close(self, conn, cursor):
        if cursor is not None:
            cursor.close()
        if self.pool is not None:
            self.pool.putconn(conn)

    def close_all(self):
        if self.pool is not None:
            self.pool.closeall()

    def select(self, sql, one=False):
        conn, cursor = self.connect()
        if conn is None and cursor is None:
            return () if one else []

        try:
            cursor.execute(sql)
        except Exception as err:
            error_info(err)
            self.init()
            self.close(conn, cursor)
            return () if one else []

        result = cursor.fetchone() if one else cursor.fetchall()
        self.close(conn, cursor)
        return result

    def execute(self, sql, value=None):
        conn, cursor = self.connect()
        if conn is None and cursor is None:
            return
        try:
            cursor.execute(sql, value)
            conn.commit()
            self.close(conn, cursor)
        except Exception as err:
            error_info(err)
            conn.rollback()


class MySQLConnectionPool:
    def __init__(self, config):
        self.config = config
        self.init()

    def init(self):
        try:
            self.pool = PooledDB(
                creator=pymysql,  # 使用链接数据库的模块
                mincached=10,  # 初始化时，链接池中至少创建的链接，0表示不创建
                maxconnections=0,  # 连接池允许的最大连接数，0和None表示不限制连接数
                blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
                host=self.config['host'],
                port=int(self.config['port']),
                user=self.config['user'],
                password=self.config['password'],
                database=self.config['database']
            )
        except Exception as err:
            self.pool = None
            error_info(err)

    def open(self):
        self.conn = self.pool.connection()
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)  # 表示读取的数据为字典类型
        return self.conn, self.cursor

    def close(self, cursor, conn):
        cursor.close()
        conn.close()

    def select_one(self, sql, *args):
        """查询单条数据"""
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchone()
        self.close(conn, cursor)
        return result

    def select_all(self, sql, args):
        """查询多条数据"""
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchall()
        self.close(conn, cursor)
        return result

    def insert_one(self, sql, args):
        """插入单条数据"""
        self.execute(sql, args, isNeed=True)

    def insert_all(self, sql, datas):
        """插入多条批量插入"""
        conn, cursor = self.open()
        try:
            cursor.executemany(sql, datas)
            conn.commit()
            return {'result': True, 'id': int(cursor.lastrowid)}
        except Exception as err:
            conn.rollback()
            return {'result': False, 'err': err}

    def update_one(self, sql, args):
        """更新数据"""
        self.execute(sql, args, isNeed=True)

    def delete_one(self, sql, *args):
        """删除数据"""
        self.execute(sql, args, isNeed=True)

    def execute(self, sql, args, isNeed=False):
        """
        执行
        :param isNeed 是否需要回滚
        """
        conn, cursor = self.open()
        if isNeed:
            try:
                cursor.execute(sql, args)
                conn.commit()
            except:
                conn.rollback()
        else:
            cursor.execute(sql, args)
            conn.commit()
        self.close(conn, cursor)

class ClickHouseConnectionPool:
    def __init__(self, config):
        self.config = config
        self.init()

    def init(self):
        try:
            connection_str = 'clickhouse://{user}:{password}@{server_host}:{port}/{db}'.format(**self.config)
            self.engine = create_engine(connection_str, pool_size=300, pool_recycle=3600, pool_timeout=20)
        except Exception as err:
            self.engine = None
            error_info(err)

    def excute(self,sql):
        session = make_session(self.engine)
        cursor = session.execute(sql)
        data = cursor.fetchall()
        cursor.close()
        session.close()
        return data


#
# odbc在linux上的依赖包
# unixODBC unixODBC-devel libtool-ltdl libtool-ltdl-devel
# odbc_pool = None
# dsn = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=192.168.180.51;DATABASE=KJ83-2012;UID=sa;PWD=Kj83n_2018"
#
#
# async def init_odbc_pool():
#     global odbc_pool
#     odbc_pool = await aioodbc.create_pool(dsn)
#
#
# async def query_gas_admin():
#     global odbc_pool
#     await init_odbc_pool()
#     async with odbc_pool.acquire() as conn:
#         cur = await conn.cursor()
#         await cur.execute("SELECT * FROM View_Gas_admin")
#         r = await cur.fetchall()
#         await cur.close()
#         await conn.close()
#         return r


# if __name__ == '__main__':
#     asyncio.run(init_odbc_pool())
#     result = asyncio.run(query_gas_admin())
#     # loop = asyncio.get_event_loop()
#     # loop.run_until_complete(init_odbc_pool())
#     # result = loop.run_until_complete(query_gas_admin())
#     print(result)
